package com.dynamic.mybatis.core.generator.method;

import com.dynamic.mybatis.core.enums.ReturnType;
import com.dynamic.mybatis.core.generator.MapperMethod;
import com.dynamic.mybatis.core.generator.InjectorMethod;
import com.dynamic.mybatis.core.generator.InjectorHelper;
import com.dynamic.mybatis.core.generator.helper.UpdateInjectorHelper;
import com.dynamic.mybatis.core.generator.helper.WhereInjectorHelper;
import com.dynamic.mybatis.core.metadata.DynamicMappedStatement;
import com.dynamic.mybatis.core.metadata.MappedStatementTable;
import org.apache.ibatis.builder.MapperBuilderAssistant;
import org.apache.ibatis.executor.keygen.NoKeyGenerator;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.scripting.LanguageDriver;
import org.apache.ibatis.session.Configuration;

import java.util.Map;

/**
 * @Description
 * @Author xs
 * @Date 2023/4/14 10:12
 */
public class Update extends InjectorMethod {

    public Update() {
        super(MapperMethod.StandardMapperMethod.update);
    }

    public Update(MapperMethod mapperMethod) {
        super(mapperMethod);
    }

    @Override
    public String builderScriptSql(String namespace, MappedStatementTable table, MapperBuilderAssistant assistant) {
        String sql = String.format(getSqlTemplate(), table.getTableName(),
                NEWLINE + SPACE + UpdateInjectorHelper.sqlSet(true, false, table, false, null, null),
                WhereInjectorHelper.sqlWhereWrapper(true, table), InjectorHelper.sqlComment());


        return sql;
    }

    @Override
    public DynamicMappedStatement injectMappedStatement(String namespace, MappedStatementTable table, MapperBuilderAssistant assistant) {
        LanguageDriver languageDriver = assistant.getConfiguration().getDefaultScriptingLanguageInstance();
        Configuration configuration = assistant.getConfiguration();
        String sql = builderScriptSql(namespace, table, assistant);
        SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, Map.class);

        MappedStatement ms = super.addMappedStatement(assistant, table, namespace, sqlSource, SqlCommandType.UPDATE, Map.class, null, Integer.class, NoKeyGenerator.INSTANCE, null, null);

        return builderDynamicMappedStatement(namespace, table, ms, sql);
    }
}